package com.adopapa.nezhacloud.register.controller;

import java.io.IOException;
import java.io.InputStream;
import java.time.Instant;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.exception.ExceptionUtils;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import com.adopapa.importexcel.Importer;
import com.adopapa.importexcel.SheetContent;
import com.adopapa.nezhacloud.common.RestResponse;
import com.adopapa.nezhacloud.common.Tools;
import com.adopapa.nezhacloud.ddd.conf.AppConstants;
import com.adopapa.nezhacloud.ddd.controller.BaseController;
import com.adopapa.nezhacloud.register.domain.StudyStat;
import com.adopapa.nezhacloud.register.service.DataSystemService;
import com.adopapa.nezhacloud.register.service.StudyStatService;

import jakarta.servlet.http.HttpServletRequest;

@RestController
@RequestMapping("/register/studystat")
public class StudyStatController extends BaseController {

	@Autowired
	private StudyStatService studyStatService;
	@Autowired
	private DataSystemService dataSystemService;

	@GetMapping(path = "/studystats/{pageNo}", produces = MediaType.APPLICATION_JSON_VALUE)
	public RestResponse getStudyStatPage(@RequestHeader String authorization, //
			@PathVariable Integer pageNo, //
			@RequestParam(required = false) String userId, //
			@RequestParam(required = false) String nickName, //
			@RequestParam(required = false) String collectCode, //
			@RequestParam(required = false) String itemName, //
			@RequestParam(required = false) String courseType, //
			@RequestParam(required = false) Long amountToSec, //
			@RequestParam(required = false) String progress, //
			@RequestParam(required = false) Integer courseEnded, //
			@RequestParam(required = false) Long validTimeSec, //
			@RequestParam(required = false) String cellphone, //
			@RequestParam(required = false) String name, //
			@RequestParam(required = false) Integer pageSize) {

		StudyStat studyStat = new StudyStat();

		studyStat.setUserId(userId);
		studyStat.setNickName(nickName);
		studyStat.setCollectCode(collectCode);
		studyStat.setItemName(itemName);
		studyStat.setCourseType(courseType);
		studyStat.setAmountToSec(amountToSec);
		studyStat.setProgress(progress);
		studyStat.setCourseEnded(courseEnded);
		studyStat.setValidTimeSec(validTimeSec);
		studyStat.setCellphone(cellphone);
		studyStat.setName(name);

		pageSize = Tools.empty(pageSize) ? AppConstants.DEFAULT_PAGE_SIZE : pageSize;

		Page<StudyStat> page = studyStatService.getStudyStatPage(pageNo, pageSize, studyStat);

		return RestResponse.ok(page);
	}

	@GetMapping(path = "/studystat/{id}", produces = MediaType.APPLICATION_JSON_VALUE)
	public RestResponse getHappyDemo(@RequestHeader String authorization, //
			@PathVariable String id) {
		StudyStat studyStat = studyStatService.getStudyStatById(id);
		return RestResponse.ok(studyStat);
	}

	@PostMapping(path = "/studystats", produces = MediaType.APPLICATION_JSON_VALUE, //
			consumes = MediaType.APPLICATION_JSON_VALUE)
	public RestResponse saveStudyStat(@RequestHeader String authorization, //
			@RequestBody Map<String, Object> params) {

		String id = getMapValue(params, "id", String.class);

		String userId = getMapValue(params, "userId", String.class);
		String nickName = getMapValue(params, "nickName", String.class);
		String collectCode = getMapValue(params, "collectCode", String.class);
		String itemName = getMapValue(params, "itemName", String.class);
		String courseType = getMapValue(params, "courseType", String.class);
		String amountToStr = getMapValue(params, "amountToStr", String.class);
		Long amountToSec = getMapValue(params, "amountToSec", Long.class);
		String progress = getMapValue(params, "progress", String.class);
		Integer courseEnded = getMapValue(params, "courseEnded", Integer.class);
		String startTime = getMapValue(params, "startTime", String.class);
		String validTimeStr = getMapValue(params, "validTimeStr", String.class);
		Long validTimeSec = getMapValue(params, "validTimeSec", Long.class);
		String endTime = getMapValue(params, "endTime", String.class);
		String cellphone = getMapValue(params, "cellphone", String.class);
		String name = getMapValue(params, "name", String.class);

		if (Tools.empty(userId)) {
			throw new RuntimeException("用户ID不能为空");
		}
		if (Tools.empty(nickName)) {
			throw new RuntimeException("用户昵称不能为空");
		}
		if (Tools.empty(collectCode)) {
			throw new RuntimeException("最近采集号码不能为空");
		}
		if (Tools.empty(itemName)) {
			throw new RuntimeException("单品名称不能为空");
		}
		if (Tools.empty(courseType)) {
			throw new RuntimeException("课程类型不能为空");
		}
		if (Tools.empty(amountToStr)) {
			throw new RuntimeException("累计学习时长不能为空");
		}
		if (Tools.empty(amountToSec)) {
			throw new RuntimeException("累计学习时长(秒)不能为空");
		}
		if (Tools.empty(progress)) {
			throw new RuntimeException("学习进度不能为空");
		}
		if (Tools.empty(courseEnded)) {
			throw new RuntimeException("课程完成数不能为空");
		}
		if (Tools.empty(startTime)) {
			throw new RuntimeException("首次学习时间不能为空");
		}
		if (Tools.empty(validTimeStr)) {
			throw new RuntimeException("有效学习时长不能为空");
		}
		if (Tools.empty(validTimeSec)) {
			throw new RuntimeException("有效学习时长(秒)不能为空");
		}
		if (Tools.empty(endTime)) {
			throw new RuntimeException("完成时间不能为空");
		}
		if (Tools.empty(cellphone)) {
			throw new RuntimeException("手机号码不能为空");
		}
		if (Tools.empty(name)) {
			throw new RuntimeException("学员姓名不能为空");
		}

		StudyStat studyStat = null;
		if (Tools.empty(id)) {
			studyStat = new StudyStat();
			studyStat.setCreateTime(Instant.now());
		} else {
			studyStat = studyStatService.getStudyStatById(id);
			if (Tools.empty(studyStat)) {
				throw new RuntimeException("指定id对应信息不存在");
			}
		}
		StudyStat existed = studyStatService.getStudyStatByUserId(userId);
		if (!Tools.empty(existed) && !existed.getId().equals(id)) {
			throw new RuntimeException("userId已经存在");
		}
		existed = studyStatService.getStudyStatByCellphone(cellphone);
		if (!Tools.empty(existed) && !existed.getId().equals(id)) {
			throw new RuntimeException("cellphone已经存在");
		}

		studyStat.setUserId(userId);
		studyStat.setNickName(nickName);
		studyStat.setCollectCode(collectCode);
		studyStat.setItemName(itemName);
		studyStat.setCourseType(courseType);
		studyStat.setAmountToStr(amountToStr);
		studyStat.setAmountToSec(amountToSec);
		studyStat.setProgress(progress);
		studyStat.setCourseEnded(courseEnded);
//		studyStat.setStartTime(startTime);
		studyStat.setValidTimeStr(validTimeStr);
		studyStat.setValidTimeSec(validTimeSec);
//		studyStat.setEndTime(endTime);
		studyStat.setCellphone(cellphone);
		studyStat.setName(name);

		studyStatService.saveStudyStat(studyStat);

		return RestResponse.ok();

	}

	@DeleteMapping(path = "/studystat/{id}", produces = MediaType.APPLICATION_JSON_VALUE)
	public RestResponse deleteStudyStat(@RequestHeader String authorization, //
			@PathVariable String id) {
		try {
			studyStatService.deleteStudyStat(id);
		} catch (Exception e) {
			logger.error(ExceptionUtils.getStackTrace(e));
		}

		return RestResponse.ok();
	}

	@PostMapping(path = "/import", consumes = MediaType.MULTIPART_FORM_DATA_VALUE, //
			produces = MediaType.APPLICATION_JSON_VALUE)
	public RestResponse importStudyStat(@RequestHeader String authorization, HttpServletRequest request) {

		try {
			MultipartFile multipartFile = ((MultipartHttpServletRequest) request).getFile("file");
			Workbook workbook = getExcleFile(multipartFile.getInputStream(), //
					multipartFile.getOriginalFilename());
			Sheet sheet = workbook.getSheetAt(0);
			SheetContent sheetContent = Importer.praseSheet(sheet);
			List<String> result = Importer.validateSheet(sheetContent, StudyStat.class);

			if (!Tools.empty(result)) {
				return RestResponse.ok(result);
			}

			List<StudyStat> studyStats = Importer.buildObjects(sheetContent, StudyStat.class);

			dataSystemService.batchSaveStudyStat(studyStats);

		} catch (Exception e) {
			logger.error(ExceptionUtils.getStackTrace(e));
		}

		return RestResponse.ok();
	}

	private static Workbook getExcleFile(InputStream is, String fileName) throws IOException {
		// BufferedInputStream in = new
		// BufferedInputStream(multipartFile.getInputStream());
		// 打开HSSFWorkbook
		// String fileName = multipartFile.getOriginalFilename();
		Workbook wb = null;
		if (fileName.endsWith(".xlsx")) {
			wb = new XSSFWorkbook(is);
		} else if (fileName.endsWith(".xls")) {
			wb = new HSSFWorkbook(is);
		} else {
			throw new RuntimeException("不是EXCEL文件");
		}
		return wb;
	}
	
	
	@GetMapping(path = "/upstudent", produces = MediaType.APPLICATION_JSON_VALUE)
	public RestResponse upstudent(@RequestHeader String authorization) {
		dataSystemService.asyncUpstudent();
		return RestResponse.ok();
	}
	
	
	@GetMapping(path = "/batchenroll", produces = MediaType.APPLICATION_JSON_VALUE)
	public RestResponse batchEnroll(@RequestHeader String authorization) {
		dataSystemService.asyncBatchEnroll();
		return RestResponse.ok();
	}
	
	
	
	
	

}
